<template>
  <div>
    <!-- 区域一 -->
    <a-card :bordered="false" :body-style="{marginBottom: '20px'}">
      <a-form :form="form">
        <h4 class="form-title"><b>基本信息</b></h4>
        <!-- 第一行 -->
        <a-row :gutter="24" :style="{ marginBottom: '16px' }">
          <a-col :span="6">
            <label class="labeltitle">业务名称:</label> 
            <span class="item-content">{{ this.$route.query.app_name }}</span>
          </a-col>
          <a-col :span="6">
            <label class="labeltitle">业务代码:</label> 
            <span class="item-content">{{ this.$route.query.app_alias }}</span>
          </a-col>
          <a-col :span="6">
            <label class="labeltitle">支持厂商:</label> 
            <span class="item-content">{{ this.$route.query.isv_name }}</span>
          </a-col>
          <a-col :span="6">
            <label class="labeltitle">运行状态:</label> 
            <span class="item-content">
              <a-badge status="success" text="正常" v-if="this.$route.query.status === '0'"/>
              <a-badge status="warning" text="不正常" v-if="this.$route.query.status === '1'"/>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-row :gutter="24">
      <!-- 区域二: 告警事件分布 -->
      <a-col :xl="8" :lg="8" :md="8" :sm="24" :style="{marginBottom: '10px'}">
        <a-card
          :bordered="false"
          :style="{marginBottom: '20px'}"
          size="default" 
          title="告警事件分布">
          <a-spin :spinning="loading">
            <a-table
              row-key="severity"
              size="default"
              :columns="evtColumns"
              :dataSource="evtData"
              :pagination="{ pageSize: 3 }"
            >
              <span slot="operate" slot-scope="text, record">
                <template>
                  <a><router-link :to="{ name: 'hostsDetails', query: { location: record.location } }">详情</router-link></a>
                </template>
              </span>
            </a-table>
          </a-spin>
        </a-card>
      </a-col>
      <!-- 区域三: 主动探测 -->
      <a-col :xl="8" :lg="8" :md="8" :sm="24" :style="{marginBottom: '10px'}">
        <a-card
          :bordered="false"
          :style="{marginBottom: '20px'}"
          size="default" 
          title="URL主动探测">
          <a-spin :spinning="loading">
            <a-table
              row-key="scenario"
              size="default"
              :columns="urlColumns"
              :dataSource="urlData"
              :pagination="{ pageSize: 3 }"
            >
              <span slot="rsp_code" slot-scope="text">
                <a-badge status="success" :text="text" v-if="text === '200'"/>
                <a-badge status="warning" :text="text" v-if="text !== '200'"/>
              </span>
              <!-- 示例
              <span slot="rsp_code" slot-scope="text">
                <span status="success" v-if="text === 200">200</span>
                <span status="warning" v-if="text === 404">404</span>
              </span>
              -->
              <!--
              <span slot="operate" slot-scope="text, record">
                <template>
                  <a><router-link :to="{ name: 'hostsDetails', query: { location: record.location } }">图形</router-link></a>
                </template>
              </span>
              -->
            </a-table>
          </a-spin>
        </a-card>
      </a-col>
      <!-- 区域四: 关键服务状态 -->
      <a-col :xl="8" :lg="8" :md="8" :sm="24" :style="{marginBottom: '10px'}">
        <a-card
          :bordered="false"
          :style="{marginBottom: '20px'}"
          size="default" 
          title="关键服务状态">
          <a-spin :spinning="loading">
            <a-table
              row-key="svc_desc"
              size="default"
              :columns="svcColumns"
              :dataSource="svcData"
              :pagination="{ pageSize: 3 }"
            >
              <span slot="status" slot-scope="text">
                <a-badge status="warning" text="Down (0)" v-if="text === '0'"/>
                <a-badge status="success" text="Up (1)" v-if="text === '1'"/>
              </span>
            </a-table>
          </a-spin>
        </a-card>
      </a-col>
    </a-row>  
    <!-- 区域五: 操作系统列表 --> 
    <a-card
      :bordered="false"
      :style="{ marginBottom: '20px'}"
      size="default" 
      title="操作系统列表">
      <a-spin :spinning="loading">
        <a-table
          row-key="node"
          size="default"
          :columns="hostColumns"
          :dataSource="hostData"
          :pagination="{ pageSize: 10 }"
        >
          <span slot="status" slot-scope="text">
            <a-badge status="success" text="正常" v-if="text === 0"/>
            <a-badge status="warning" text="不正常" v-if="text === 1"/>
          </span>
          <span slot="dictValue" slot-scope="text">
            <ellipsis :length="80" tooltip>{{ text }}</ellipsis>
          </span>
          <span slot="operate" slot-scope="text, record">
            <template>
              <a><router-link :to="{ name: 'hostsDetails', query: { node: record.node, node_alias: record.node_alias, app_name: record.app_name, pcs_name: record.pcs_name, location: record.location, status: record.status, host_id: record.zbx_hostid } }">详情</router-link></a>
            </template>
          </span>
        </a-table>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { executeBySqlCmd } from '@/api/objectserver'
import { sqlFindOne } from '@/api/sql'
import { monitorObjectStatus } from '@/api/monitor'

export default {
  components: {
    STable,
    Ellipsis
  },

  data () {
    return {
      loading: false,
      visible: false,
      confirmLoading: false,
      scrollx: 1500,

      labelCol: {
        xs: { span: 24 },
        sm: { span: 9 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 }
      },
      details: {},

      // 分页属性
      pagination: {
        page: 0,
        defaultPageSize: 10,
        pageNo: 1,
        pageSize: 10, // 默认每页显示数量
        showSizeChanger: true, // 显示可改变每页数量
        showQuickJumper: true, // 是否可以快速跳转至某页
        pageSizeOptions: ['10', '20', '50', '100'], // 每页数量选项
        showTotal: total => this.$t('pagination.total') + ` ${total} ` + this.$t('pagination.items'), // 分页中显示总的数据
        total: 0 // 总条数
      },

      /*
       * 告警事件根据严重级别分布
       */

      evtColumns: [
        {
          title: '严重级别',
          dataIndex: 'severity',
          key: 'severity'
        },
        {
          title: '告警数量',
          dataIndex: 'count',
          key: 'count'
        },
        {
          title: '操作',
          fixed: 'right',
          width: '100px',
          dataIndex: 'operate',
          scopedSlots: { customRender: 'operate' }
        }
      ],

      evtData: [],

      /*
       * 关键服务状态列表
       */

      svcColumns: [
        {
          title: '主机',
          dataIndex: 'host_name',
          key: 'host_name'
        },
        {
          title: '服务名称',
          dataIndex: 'svc_desc',
          key: 'svc_desc'
        },
        {
          title: '运行状态',
          dataIndex: 'status',
          key: 'status',
          scopedSlots: { customRender: 'status' }
        }
      ],

      svcData: [],

      /*
       * URL主动探测信息列表
       */

      urlColumns: [
        {
          title: 'Scenario',
          dataIndex: 'scenario',
          key: 'scenario'
        },
        {
          title: 'URL',
          dataIndex: 'step_addr',
          key: 'step_addr'
        },
        /*
        {
          title: '响应时间',
          fixed: 'right',
          width: '100px',
          dataIndex: 'operate',
          scopedSlots: { customRender: 'operate' }
        },
        */
        {
          title: '响应状态',
          dataIndex: 'rsp_code',
          key: 'rsp_code',
          scopedSlots: { customRender: 'rsp_code' }
        }
       
      ],

      urlData: [],

      /*
       * 操作系统信息列表
       */

      hostColumns: [
        {
          title: '主机名称',
          dataIndex: 'node',
          scopedSlots: { customRender: 'node' },
          width: 200
        }, {
          title: '主机地址',
          dataIndex: 'node_alias',
          width: 150
        }, {
          title: '所属平台',
          dataIndex: 'pcs_name',
          width: 150
        }, {
          title: '数据中心',
          dataIndex: 'location',
          width: 150
        }, {
          title: '日期时间',
          dataIndex: 'timestamp',
          width: 250
        }, {
          title: 'CPU使用率',
          dataIndex: 'cpu_usage',
          width: 150
        }, {
          title: '内存使用率',
          dataIndex: 'mem_usage',
          width: 150
        }, {
          title: '运行状态',
          dataIndex: 'status',
          width: 100,
          scopedSlots: { customRender: 'status' }
        }, {
          title: '操作',
          fixed: 'right',
          width: '100px',
          dataIndex: 'operate',
          scopedSlots: { customRender: 'operate' }
        }
      ],

      hostData: [],
      
      form: this.$form.createForm(this)
    }
  },

  filters: {},
  computed: {},

  mounted () {
    // 测试用: 模拟静态数据
    // this.getStaticData()

    // 生产用: 发起API请求
    this.getEvtDataByApp()
    this.getUrlDataByApp(this.pagination.page, this.pagination.pageSize)
    this.getSvcDataByApp(this.pagination.page, this.pagination.pageSize)
    this.getHostDataByApp(this.pagination.page, this.pagination.pageSize)
  },

  methods: {
    getStaticData () {
      this.urlData = [
        { 
          scenario: 'remedy-url-probing',
          step_addr: 'http://172.16.0.44:8080/',
          rsp_time: '2.95 (ms)',
          rsp_code: 200
        },
        { 
          scenario: 'zabbix-url-probing',
          step_addr: 'http://172.16.0.43/',
          rsp_time: '2.95 (ms)',
          rsp_code: 404
        }
      ]

      this.svcData = [
        { 
          host_name: 'omc_test1',
          svc_desc: 'PostgreSQL Status',
          status: 0
        },
        { 
          host_name: 'omc_test1',
          svc_desc: 'Zabbix agent availability',
          status: 1
        }
      ]

      this.loading = false
    },

    /*
     * 数据来源: 关键服务监控(Zabbix)
     */

    async getSvcDataByApp (page, size) {
      this.svcData = await this.getSvcListByApp(page, size)
      this.pagenation.total = await this.getSvcTotalByApp()
    },

    getSvcListByApp (page, size) {
      const params = {
        obj_type: 'svcs',
        sql_stmt: "select item_id, item_key, host_id, host_name, svc_name, svc_desc from mon.zbx_svc_items where app_alias='" + this.$route.query.app_alias + "'" + ' offset ' + page * size + ' limit ' + size
      }

      return new Promise((resolve, reject) => {
        monitorObjectStatus(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },

    getSvcTotalByApp () {
      const params = {
        sql: "select count(*) as total from mon.zbx_svc_items where app_alias='" + this.$route.query.app_alias + "'"
      }
      return new Promise((resolve, reject) => {
        sqlFindOne(params).then(
          (res) => {
            resolve(res.total)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },

    /*
     * 数据来源: URL主动探测(Zabbix)
     */

    async getUrlDataByApp (page, size) {
      this.urlData = await this.getUrlListByApp(page, size)
      this.pagenation.total = await this.getUrlTotalByApp()
    },

    getUrlListByApp (page, size) {
      const params = {
        obj_type: 'urls',
        sql_stmt: "select item_id, item_key, host_id, scenario, step_name, step_addr from mon.zbx_web_items where item_key='web.test.rspcode' and app_alias='" + this.$route.query.app_alias + "'" + ' offset ' + page * size + ' limit ' + size
      }

      return new Promise((resolve, reject) => {
        monitorObjectStatus(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },

    getUrlTotalByApp () {
      const params = {
        sql: "select count(*) as total from mon.zbx_web_items where app_alias='" + this.$route.query.app_alias + "'"
      }
      return new Promise((resolve, reject) => {
        sqlFindOne(params).then(
          (res) => {
            resolve(res.total)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },

    /*
     * 数据来源: API封装
     */

    async getHostDataByApp (page, size) {
      this.hostData = await this.getHostListByApp(page, size)
      this.pagination.total = await this.getHostTotalByApp()
    },

    getHostListByApp (page, size) {
      const params = {
        obj_type: 'hosts',
        sql_stmt: "select node, node_alias, app_name, pcs_name, location from cmdb.hosts where app_name='" + this.$route.query.app_name + "'" + ' offset ' + page * size + ' limit ' + size
      }
      return new Promise((resolve, reject) => {
        monitorObjectStatus(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },

    getHostTotalByApp () {
      const params = {
        sql: "select count(*) as total from cmdb.hosts where app_name='" + this.$route.query.app_name + "'"
      }
      return new Promise((resolve, reject) => {
        sqlFindOne(params).then(
          (res) => {
            resolve(res.total)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },

    /*
     * 数据来源: OMNIbus/ObjectServer
     */

    async getEvtDataByApp () {
      this.count_sev = await this.getCountBySeverity()
      const _this = this // 否则foreach内提示异常
      
      this.count_sev.forEach(function (item) {
        if (item.agg_key === 0) {
           _this.evtData.push({
            severity: 'Clear', 
            count: item.agg_value
          })
        } else if (item.agg_key === 3) {
          _this.evtData.push({
            severity: 'Warning', 
            count: item.agg_value
          })
        } else if (item.agg_key === 5) {
          _this.evtData.push({
            severity: 'Critical', 
            count: item.agg_value
          })
        } 
      })
    },

    getCountBySeverity () {
      const params = {
        sqlcmd: "select count(*) as agg_value, Severity as agg_key from alerts.status where Severity in (0,3,5) and app_name='" + this.$route.query.app_name + "' group by agg_key"
      }
      return new Promise((resolve, reject) => {
        executeBySqlCmd(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .form-title {
    color: rgba(0,0,0,.85);
    font-size: 15px;
    font-weight: 500;
    margin-bottom: 20px;
  }
  .labeltitle{
    margin-right: 10px;
  }
  .item-content{
    color: #999;
  }
</style>
